﻿using System;
using System.Windows.Forms;
using System.Threading;

namespace VisualPureBasicIDE.CoreGUI
{
    public partial class ActionProgressDialog : Form
    {
        public event EventHandler AbortRequest;
        private bool _overrideClose;

        public ActionProgressDialog()
        {
            InitializeComponent();
        }

        public ActionProgressDialog(string description)
        {
            InitializeComponent();

            Description = String.IsNullOrEmpty(description) ? Description : description; // Quite confusing, isn't it?
        }
        
        /// <summary>
        /// Gets or sets the description that is displayed in the ActionProgressDialog
        /// </summary>
        public string Description
        {
            get
            {
                return labelAction.Text;
            }
            set
            {
                labelAction.Text = value;
            }
        }

        private void formActionProgress_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_overrideClose) return;

            e.Cancel = true;

            if (AbortRequest != null)
                AbortRequest(this, new EventArgs());
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            if (AbortRequest != null)
                AbortRequest(this, new EventArgs());
        }

        #region ActionProgressDialog helpers

        public static void ShowMultithreaded(ActionProgressDialog ad)
        {
            var t = new Thread(ShowNewActionProgressDialog);
            if (t.TrySetApartmentState(ApartmentState.STA))
                t.Start(ad);
        }

        private static void ShowNewActionProgressDialog(object param)
        {
            if (param != null && param.GetType() == typeof(ActionProgressDialog))
                Application.Run((ActionProgressDialog)param);
        }

        private delegate void CloseActionProgressDialogCallback(ActionProgressDialog ad);

        public static void CloseMultithreaded(ActionProgressDialog apd)
        {
            if (apd.InvokeRequired)
            {
                // Callback needed ...
                var d = new CloseActionProgressDialogCallback(CloseMultithreaded);
                apd.Invoke(d, new object[] { apd });
            }
            else
            {
                apd._overrideClose = true;
                apd.Close();
                Application.ExitThread();
            }
        }

        #endregion
    }
}